package com.hmi.simulatedrive.fragment

import android.app.Service
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import com.hmi.simulatedrive.utils.FragmentBackHandler


open class BaseFragment: Fragment(), FragmentBackHandler {
    override fun onAttach(context: Context) {
        super.onAttach(context)
        val callback: OnBackPressedCallback = object : OnBackPressedCallback(
            true // default to enabled
        ) {
            override fun handleOnBackPressed() {
                if (parentFragmentManager.backStackEntryCount>0) {
                    parentFragmentManager.popBackStack()
                }
            }
        }

        //获取Activity的返回键分发器添加回调
        requireActivity().onBackPressedDispatcher.addCallback(
            this,  // LifecycleOwner
            callback
        )
    }

    override fun onBackPressed(): Boolean {
        return false
    }

    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    open fun showInput(et: EditText) {
        et.requestFocus()
        val imm = requireContext().getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
        imm!!.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT)
    }

    /**
     * 隐藏键盘
     */
    protected open fun hideInput() {
        val imm = requireContext().getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
        val v: View = requireActivity().getWindow().peekDecorView()
        if (null != v) {
            imm!!.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }
}